<template>
  <div class="project-initiation">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon><DocumentAdd /></el-icon>
          项目立项
        </h1>
        <div class="header-actions">
          <el-button @click="saveDraft">
            <el-icon><Document /></el-icon>
            保存草稿
          </el-button>
          <el-button type="primary" @click="submitApplication">
            <el-icon><Check /></el-icon>
            提交申请
          </el-button>
        </div>
      </div>
    </div>

    <!-- 立项表单 -->
    <div class="form-container">
      <el-card class="form-card">
        <el-form
          ref="initiationForm"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          size="default"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><InfoFilled /></el-icon>
              基本信息
            </div>
            
            <el-row :gutter="20">
              <el-col :xs="24" :md="12">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input
                    v-model="formData.projectName"
                    placeholder="请输入项目名称"
                    maxlength="100"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="12">
                <el-form-item label="项目编号" prop="projectCode">
                  <el-input
                    v-model="formData.projectCode"
                    placeholder="系统自动生成或手动输入"
                    maxlength="20"
                  >
                    <template #append>
                      <el-button @click="generateCode">生成</el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :xs="24" :md="12">
                <el-form-item label="项目类型" prop="projectType">
                  <el-select v-model="formData.projectType" placeholder="请选择项目类型" style="width: 100%">
                    <el-option label="产品开发" value="product" />
                    <el-option label="系统集成" value="integration" />
                    <el-option label="基础设施" value="infrastructure" />
                    <el-option label="研发创新" value="research" />
                    <el-option label="运营改进" value="operation" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="12">
                <el-form-item label="优先级" prop="priority">
                  <el-select v-model="formData.priority" placeholder="请选择优先级" style="width: 100%">
                    <el-option label="高" value="high">
                      <span style="color: #F56C6C">高</span>
                    </el-option>
                    <el-option label="中" value="medium">
                      <span style="color: #E6A23C">中</span>
                    </el-option>
                    <el-option label="低" value="low">
                      <span style="color: #909399">低</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="项目描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                :rows="4"
                placeholder="请详细描述项目背景、目标和主要内容"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </div>

          <!-- 项目团队 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><User /></el-icon>
              项目团队
            </div>
            
            <el-row :gutter="20">
              <el-col :xs="24" :md="12">
                <el-form-item label="项目经理" prop="projectManager">
                  <el-select v-model="formData.projectManager" placeholder="请选择项目经理" style="width: 100%">
                    <el-option
                      v-for="manager in managerList"
                      :key="manager.id"
                      :label="manager.name"
                      :value="manager.id"
                    >
                      <div class="manager-option">
                        <span>{{ manager.name }}</span>
                        <span class="manager-dept">{{ manager.department }}</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="12">
                <el-form-item label="申请部门" prop="department">
                  <el-select v-model="formData.department" placeholder="请选择申请部门" style="width: 100%">
                    <el-option label="技术部" value="tech" />
                    <el-option label="产品部" value="product" />
                    <el-option label="运营部" value="operation" />
                    <el-option label="市场部" value="marketing" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="团队成员">
              <div class="team-members">
                <div class="member-list">
                  <el-tag
                    v-for="member in formData.teamMembers"
                    :key="member.id"
                    closable
                    @close="removeMember(member.id)"
                    class="member-tag"
                  >
                    {{ member.name }} ({{ member.role }})
                  </el-tag>
                </div>
                <el-button type="primary" plain @click="showAddMember = true">
                  <el-icon><Plus /></el-icon>
                  添加成员
                </el-button>
              </div>
            </el-form-item>
          </div>

          <!-- 时间计划 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><Calendar /></el-icon>
              时间计划
            </div>
            
            <el-row :gutter="20">
              <el-col :xs="24" :md="12">
                <el-form-item label="计划开始" prop="startDate">
                  <el-date-picker
                    v-model="formData.startDate"
                    type="date"
                    placeholder="选择开始日期"
                    style="width: 100%"
                    :disabled-date="disabledStartDate"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="12">
                <el-form-item label="计划结束" prop="endDate">
                  <el-date-picker
                    v-model="formData.endDate"
                    type="date"
                    placeholder="选择结束日期"
                    style="width: 100%"
                    :disabled-date="disabledEndDate"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :xs="24" :md="12">
                <el-form-item label="项目周期">
                  <el-input :value="projectDuration" readonly>
                    <template #suffix>天</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="12">
                <el-form-item label="里程碑数量">
                  <el-input-number
                    v-model="formData.milestoneCount"
                    :min="1"
                    :max="20"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 预算信息 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><Money /></el-icon>
              预算信息
            </div>
            
            <el-row :gutter="20">
              <el-col :xs="24" :md="12">
                <el-form-item label="总预算" prop="totalBudget">
                  <el-input-number
                    v-model="formData.totalBudget"
                    :precision="2"
                    :step="1000"
                    :min="0"
                    style="width: 100%"
                  >
                    <template #suffix>元</template>
                  </el-input-number>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="12">
                <el-form-item label="预算来源" prop="budgetSource">
                  <el-select v-model="formData.budgetSource" placeholder="请选择预算来源" style="width: 100%">
                    <el-option label="公司自有资金" value="company" />
                    <el-option label="政府补贴" value="government" />
                    <el-option label="银行贷款" value="loan" />
                    <el-option label="投资资金" value="investment" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="预算明细">
              <el-table :data="formData.budgetDetails" style="width: 100%" border>
                <el-table-column prop="category" label="费用类别" width="150">
                  <template #default="{ row, $index }">
                    <el-select v-model="row.category" placeholder="选择类别" size="small">
                      <el-option label="人力成本" value="labor" />
                      <el-option label="设备采购" value="equipment" />
                      <el-option label="软件许可" value="software" />
                      <el-option label="外包服务" value="outsource" />
                      <el-option label="其他费用" value="other" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="amount" label="金额（元）" width="150">
                  <template #default="{ row, $index }">
                    <el-input-number
                      v-model="row.amount"
                      :precision="2"
                      :min="0"
                      size="small"
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="说明">
                  <template #default="{ row, $index }">
                    <el-input
                      v-model="row.description"
                      placeholder="费用说明"
                      size="small"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="{ row, $index }">
                    <el-button
                      type="danger"
                      size="small"
                      @click="removeBudgetItem($index)"
                      :disabled="formData.budgetDetails.length <= 1"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button type="primary" plain @click="addBudgetItem" style="margin-top: 10px">
                <el-icon><Plus /></el-icon>
                添加预算项
              </el-button>
            </el-form-item>
          </div>

          <!-- 风险评估 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><Warning /></el-icon>
              风险评估
            </div>
            
            <el-form-item label="主要风险" prop="risks">
              <el-input
                v-model="formData.risks"
                type="textarea"
                :rows="3"
                placeholder="请描述项目可能面临的主要风险"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="应对措施" prop="riskMitigation">
              <el-input
                v-model="formData.riskMitigation"
                type="textarea"
                :rows="3"
                placeholder="请描述风险应对和缓解措施"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>
          </div>

          <!-- 附件上传 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><Paperclip /></el-icon>
              相关附件
            </div>
            
            <el-form-item label="项目文档">
              <el-upload
                class="upload-demo"
                drag
                action="#"
                multiple
                :auto-upload="false"
                :file-list="formData.attachments"
                :on-change="handleFileChange"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 doc/docx/pdf/xls/xlsx 格式，单个文件不超过 10MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </div>
        </el-form>
      </el-card>
    </div>

    <!-- 审批流程 -->
    <el-card class="approval-card">
      <template #header>
        <div class="card-header">
          <span>审批流程</span>
          <el-tag :type="getApprovalStatusType(approvalStatus)">{{ approvalStatus }}</el-tag>
        </div>
      </template>
      
      <el-steps :active="currentStep" align-center>
        <el-step
          v-for="(step, index) in approvalSteps"
          :key="index"
          :title="step.title"
          :description="step.description"
          :status="step.status"
        />
      </el-steps>
      
      <div class="approval-history" v-if="approvalHistory.length > 0">
        <h4>审批记录</h4>
        <el-timeline>
          <el-timeline-item
            v-for="record in approvalHistory"
            :key="record.id"
            :timestamp="record.time"
            :type="record.type"
          >
            <div class="approval-record">
              <div class="record-title">{{ record.title }}</div>
              <div class="record-content">{{ record.content }}</div>
              <div class="record-user">审批人：{{ record.approver }}</div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>

    <!-- 添加成员对话框 -->
    <el-dialog v-model="showAddMember" title="添加团队成员" width="500px">
      <el-form :model="newMember" label-width="80px">
        <el-form-item label="姓名">
          <el-select v-model="newMember.id" placeholder="请选择成员" style="width: 100%" @change="onMemberSelect">
            <el-option
              v-for="user in availableUsers"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            >
              <div class="user-option">
                <span>{{ user.name }}</span>
                <span class="user-dept">{{ user.department }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="newMember.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="开发工程师" value="developer" />
            <el-option label="测试工程师" value="tester" />
            <el-option label="UI设计师" value="designer" />
            <el-option label="产品经理" value="pm" />
            <el-option label="技术专家" value="expert" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddMember = false">取消</el-button>
        <el-button type="primary" @click="addMember">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  DocumentAdd,
  Document,
  Check,
  InfoFilled,
  User,
  Calendar,
  Money,
  Warning,
  Paperclip,
  Plus,
  UploadFilled
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 响应式数据
const initiationForm = ref(null)
const showAddMember = ref(false)
const currentStep = ref(0)
const approvalStatus = ref('草稿')

// 表单数据
const formData = reactive({
  projectName: '',
  projectCode: '',
  projectType: '',
  priority: '',
  description: '',
  projectManager: '',
  department: '',
  teamMembers: [],
  startDate: '',
  endDate: '',
  milestoneCount: 3,
  totalBudget: 0,
  budgetSource: '',
  budgetDetails: [
    { category: '', amount: 0, description: '' }
  ],
  risks: '',
  riskMitigation: '',
  attachments: []
})

// 新成员数据
const newMember = reactive({
  id: '',
  name: '',
  role: '',
  department: ''
})

// 项目经理列表
const managerList = ref([
  { id: 1, name: '张三', department: '技术部' },
  { id: 2, name: '李四', department: '产品部' },
  { id: 3, name: '王五', department: '运营部' }
])

// 可用用户列表
const availableUsers = ref([
  { id: 1, name: '张三', department: '技术部' },
  { id: 2, name: '李四', department: '产品部' },
  { id: 3, name: '王五', department: '运营部' },
  { id: 4, name: '赵六', department: '设计部' },
  { id: 5, name: '钱七', department: '测试部' }
])

// 审批步骤
const approvalSteps = ref([
  { title: '提交申请', description: '项目立项申请', status: 'wait' },
  { title: '部门审批', description: '部门经理审批', status: 'wait' },
  { title: '技术评审', description: '技术委员会评审', status: 'wait' },
  { title: '高层审批', description: '高层管理审批', status: 'wait' },
  { title: '立项完成', description: '项目正式立项', status: 'wait' }
])

// 审批历史
const approvalHistory = ref([])

// 表单验证规则
const formRules = {
  projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  projectCode: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
  projectType: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  description: [{ required: true, message: '请输入项目描述', trigger: 'blur' }],
  projectManager: [{ required: true, message: '请选择项目经理', trigger: 'change' }],
  department: [{ required: true, message: '请选择申请部门', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  totalBudget: [{ required: true, message: '请输入总预算', trigger: 'blur' }],
  budgetSource: [{ required: true, message: '请选择预算来源', trigger: 'change' }]
}

// 计算属性
const projectDuration = computed(() => {
  if (formData.startDate && formData.endDate) {
    const start = new Date(formData.startDate)
    const end = new Date(formData.endDate)
    const diffTime = Math.abs(end - start)
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays
  }
  return 0
})

// 方法
const generateCode = () => {
  const timestamp = Date.now().toString().slice(-6)
  const prefix = formData.projectType ? formData.projectType.toUpperCase().slice(0, 2) : 'PR'
  formData.projectCode = `${prefix}${timestamp}`
}

const disabledStartDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

const disabledEndDate = (time) => {
  if (formData.startDate) {
    return time.getTime() < new Date(formData.startDate).getTime()
  }
  return time.getTime() < Date.now() - 8.64e7
}

const onMemberSelect = (userId) => {
  const user = availableUsers.value.find(u => u.id === userId)
  if (user) {
    newMember.name = user.name
    newMember.department = user.department
  }
}

const addMember = () => {
  if (!newMember.id || !newMember.role) {
    ElMessage.warning('请选择成员和角色')
    return
  }
  
  // 检查是否已存在
  const exists = formData.teamMembers.some(member => member.id === newMember.id)
  if (exists) {
    ElMessage.warning('该成员已在团队中')
    return
  }
  
  formData.teamMembers.push({ ...newMember })
  showAddMember.value = false
  
  // 重置表单
  Object.assign(newMember, {
    id: '',
    name: '',
    role: '',
    department: ''
  })
}

const removeMember = (memberId) => {
  const index = formData.teamMembers.findIndex(member => member.id === memberId)
  if (index > -1) {
    formData.teamMembers.splice(index, 1)
  }
}

const addBudgetItem = () => {
  formData.budgetDetails.push({
    category: '',
    amount: 0,
    description: ''
  })
}

const removeBudgetItem = (index) => {
  if (formData.budgetDetails.length > 1) {
    formData.budgetDetails.splice(index, 1)
  }
}

const handleFileChange = (file, fileList) => {
  formData.attachments = fileList
}

const getApprovalStatusType = (status) => {
  const statusMap = {
    '草稿': 'info',
    '审批中': 'warning',
    '已通过': 'success',
    '已拒绝': 'danger'
  }
  return statusMap[status] || 'info'
}

const saveDraft = async () => {
  try {
    // 这里应该调用API保存草稿
    ElMessage.success('草稿保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const submitApplication = async () => {
  try {
    await initiationForm.value.validate()
    
    await ElMessageBox.confirm(
      '确认提交项目立项申请？提交后将进入审批流程。',
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API提交申请
    approvalStatus.value = '审批中'
    currentStep.value = 1
    approvalSteps.value[0].status = 'finish'
    
    ElMessage.success('申请提交成功，已进入审批流程')
    
    // 可以跳转到项目列表或详情页
    // router.push('/project/list')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交失败:', error)
    }
  }
}

// 生命周期
onMounted(() => {
  // 初始化数据
  generateCode()
})
</script>

<style scoped>
.project-initiation {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.form-container {
  margin-bottom: 20px;
}

.form-card,
.approval-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #EBEEF5;
}

.form-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.manager-option,
.user-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.manager-dept,
.user-dept {
  font-size: 12px;
  color: #909399;
}

.team-members {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.member-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.member-tag {
  margin: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.approval-history {
  margin-top: 30px;
}

.approval-history h4 {
  margin-bottom: 16px;
  color: #303133;
}

.approval-record {
  margin-bottom: 8px;
}

.record-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.record-content {
  color: #606266;
  margin-bottom: 4px;
}

.record-user {
  font-size: 12px;
  color: #909399;
}

.upload-demo {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .project-initiation {
    padding: 10px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .team-members {
    align-items: stretch;
  }
  
  .member-list {
    justify-content: flex-start;
  }
}
</style>